<?php 
	// The die(mysql_error()) simply outputs error messages in case an error occurs.
	mysql_connect("localhost", "cs143", "");
	mysql_select_db("CS143");
	if(isset($_GET['query']))
	{
		// NOT PROTECTED AGAINST SQL ATTACKS, TRUSTING THAT INPUT IS TRUSTWORTHY
		$query = $_GET['query'];
	}
?>
<html>
<head>
<title>[Xin Wei] PHP Query for Project 1B</title>
<style>
body{
	font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
	font-size: 13px;
	line-height: 18px;
	color: #333;
	background-color: gainsboro;
}
h2 {
	font-weight: 400;
	letter-spacing: 0px;
	font-size: 26px;
	color: #222;
	margin: 1em 0 0.8em;
	line-height: 36px;
	font-family:"proxima nova","Helvetica Neue", Helvetica, Arial, sans-serif;
}
.alert {
  padding: 8px 35px 8px 14px;
  margin-bottom: 18px;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
  border: 1px solid #eed3d7;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  background-color: #f2dede;
  color: #b94a48;
}
</style>
</head>
<body>
<h2>Project 1B Query - CS143</h2>
<em>Xin Wei, CS143, April 22, 2012 <br />
Please note that tables and fields are case sensitive.</em><br /><br />

<div class="alert" style="width:500px;"><strong>Warning</strong> This application assumes all user input is trustworthy, and therefore DO NOT check the input for attacks or harmful codes.</div>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="GET">
<textarea name="query" cols="60" rows="8">
</textarea><br />

<input type="submit" value="Submit" />
</form>
<br />
<!--
<table >
  <thead>
    <tr>
      <th>a</th>
      <th>b</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>c</td>
      <td>d</td>
    </tr>
  </tbody>
  </table>-->
<?php
	if(!empty($query))
		$result = mysql_query($query);
	if($result)
	{
		?>
        <strong>Results from MySQL</strong><br /><br />
        <table border=1 cellspacing=1 cellpadding=1>
        <thead>
        <tr>
        <?php 
		$fields = mysql_num_fields($result);
		$i = 0;
		while($i < $fields)
		{
			$query1res = mysql_fetch_field($result, $i);
			echo "<th>";
			echo $query1res->name;
			echo "</th>";
			$i++;
		}
		?>
        </tr>
        </thead>
        <tbody>
        <?php
		while($row = mysql_fetch_array($result, MYSQL_NUM))
		{
			$j = 0;
			echo "<tr>";
			while($j < $fields)
			{
				echo "<td>";
				if(empty($row[$j]))
					echo "N/A";
				else
					echo $row[$j];
				echo "</td>";
				$j++;
			}
			echo "</tr>";
		}
		?>
        </tbody>
        </table>
        <?php
	}
	else
	{
		if(!empty($query))
		{
		?>
        <strong>Results from MySQL</strong><br /><br />
        <?php
			echo mysql_error();
		}
	}
?>
</body>
</html>